# -*- coding: utf8 -*-

from os import lstat, access, R_OK, X_OK
from time import sleep
from worker import Worker

class DirectoryListWorker( Worker ):

    my_query_name = "directories"

    def run ( self ):
        
        print("DirectoryListWorker: START: %s" % self.my_query_name)
        
        import os
        
        p = self.app.get_project()
        sess = p.get_session()

        while not self.stop_event.isSet():

            try:
                data = self.app.get_queue(self.my_query_name).get_nowait()
            except:
                data = None

            if data is None:
                sleep(0.01)
                continue

            dir_id, parent_path, name = data

            full_path = os.path.join( parent_path, name )

            self.app.get_stats().inc("directories_count", 1)
            st = lstat( full_path )
            idir = p.save_directory( dir_id, st.st_dev, name )

            dir_id = idir.id
            sess.expunge( idir )

            if access( full_path, R_OK + X_OK ):
                for item in os.listdir( full_path ):
                    if self.stop_event.isSet():
                        break

                    try:
                        path = os.path.join(full_path, item)
                    except:
                        print( "Directory: full_path=%r, item=%r" % (full_path, item,))
                        continue

                    st = lstat( path )

                    if os.path.isdir( path ):
                        self.app.get_dirlist_queue("directories", st.st_dev).put_nowait(
                            ( dir_id, full_path, item )
                        )
                    elif os.path.isfile( path ):
                        
                        self.app.get_filelist_queue("files", st.st_dev).put_nowait(
                            ( dir_id, full_path, item )
                        )
            
            self.app.get_stats().inc("directories_searched", 1)
            
            self.app.get_queue(self.my_query_name).task_done()
        
        print("DirectoryListWorker: STOP: %s" % self.my_query_name)

        p.close_session()

        self.stop_event.clear()
        return

